/*   The MIT License
 *   
 *   Carina Common
 *   Copyright (c) 2010-2011 Zdravko Velinov
 *   
 *   Permission is hereby granted, free of charge, to any person obtaining a copy
 *   of this software and associated documentation files (the "Software"), to deal
 *   in the Software without restriction, including without limitation the rights
 *   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *   copies of the Software, and to permit persons to whom the Software is
 *   furnished to do so, subject to the following conditions:
 *
 *   The above copyright notice and this permission notice shall be included in
 *   all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *   THE SOFTWARE.
 */

#include "carina/common/timer.hh"

#include "carina/common/exception.hh"

#include <ctime>
#include <cassert>

namespace Carina
{
Timer::Timer()
    :   m_DeltaTime(0),
        m_PauseTime(0)
{
#ifdef _WIN32
    if(!QueryPerformanceFrequency(reinterpret_cast<LARGE_INTEGER*>(&m_Frequency)))
        THROW_EXCEPTION("high-resolution performance counter is not supported by this CPU");
#elif !defined(LINUX)
#   error "Unsupported platform"
#endif
    setCurrentTime();
    reset();
}

void Timer::setCurrentTime()
{
#ifdef _WIN32
    QueryPerformanceCounter(reinterpret_cast<LARGE_INTEGER*>(&m_CurTime));
    assert(1000000000 > m_Frequency);
    m_CurTime = m_CurTime*(1000000000/m_Frequency);
#elif defined(LINUX)
    timespec tp;
    clock_gettime(CLOCK_REALTIME, &tp);
    m_CurTime = (nanosec)tp.tv_sec*1000000000 + (nanosec)tp.tv_nsec;
#else
#	error "Unsupported platform"
#endif 
}

void Timer::update()
{
    nanosec prev = m_CurTime;
    setCurrentTime();

    m_DeltaTime = m_CurTime - prev;
}

nanosec Timer::getElapsedTime() const
{
    return m_DeltaTime;
}

nanosec Timer::getTime() const
{
    return m_CurTime;
}

nanosec Timer::getGameTime() const
{
    assert(m_BeginTime <= m_CurTime);
    return m_CurTime - m_BeginTime;
}

void Timer::pause()
{
    m_PauseTime = m_CurTime;
}

void Timer::unpause()
{
    m_BeginTime += m_CurTime - m_PauseTime;
}

void Timer::reset()
{
    update();
    m_BeginTime = m_CurTime;
}
}
